﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DbMapping.Common;
using VideoCache.Server.Model;
using VideoCache.Server.DAL;
using System.Data;
using DbMapping;

namespace VideoCache.Server.BLL
{
    public partial class RoleBLL
    {
        public static bool IsUserInRole(int userId, int roleId)
        {
            Conditions cons = new Conditions();
            cons.Add(new ConditionItem(LinkType.And, UserRoleInfo.UserIdField, CompareType.Equal, userId));
            cons.Add(new ConditionItem(LinkType.And, UserRoleInfo.RoleIdField, CompareType.Equal, roleId));

            return UserRoleDAL.Exists(cons);
        }

        public static bool IsUserInRole(int userId, string role)
        {
            Conditions cons = new Conditions();
            cons.Add(new ConditionItem(LinkType.And, RoleInfo.NameField, CompareType.Equal, role));

            RoleInfo info = RoleDAL.Find(cons, null);

            if (info == null) return false;

            return IsUserInRole(userId, info.Id);
        }

        public static bool IsUserInRole(string userName, string role)
        {
            Conditions cons = new Conditions();
            cons.Add(new ConditionItem(LinkType.And, UserInfo.UserNameField, CompareType.Equal, userName));

            UserInfo user = UserBLL.Find(cons, null);

            if (user == null) return false;

            return IsUserInRole(user.Id, role);
        }

        public static void SetUserRoles(int userId, int[] roleIds)
        {
            using (IDbConnection conn = DbAccess.GetConnection())
            {
                conn.Open();
                using (IDbTransaction tran = conn.BeginTransaction())
                {
                    try
                    {
                        Conditions cons = new Conditions();
                        cons.Add(new ConditionItem(LinkType.And, UserRoleInfo.UserIdField, CompareType.Equal, userId));

                        UserRoleDAL.Delete(tran, cons);

                        foreach (int roleId in roleIds)
                        {
                            UserRoleInfo info = new UserRoleInfo();
                            info.UserId = userId;
                            info.RoleId = roleId;
                            UserRoleDAL.Add(tran, info);
                        }

                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        throw new Exception("设置用户角色出错。", ex);
                    }
                }
            }
        }
    }
}